// Global Mobile Init, fires after jQuery.Mobile has loaded.
// Note: this MUST be included before jQuery Mobile, otherwise it will never fire.
$(document).bind("mobileinit", function(){
  alert("mobileinit");
});

$(function() {
	// EVENT: SETTINGS - SAVE CLICK
	$('a#settings-save').click(function() {
		_settings.importType = $('div#settings select#bookXmlType').val();
		_settings.importUrl = $('div#settings input#bookXmlUrl').val();
		_settings.save();
	});

	// EVENT: SETTINGS - BEFORE SHOW
	$('div#settings').live('pagebeforeshow', function(event, ui){
		$('div#settings select#bookXmlType').val(_settings.importType);
		$('div#settings input#bookXmlUrl').val(_settings.importUrl);
		$('div#settings input#lastImportedURL').val(_settings.lastImportUrl);
		$('div#settings input#lastImportedTime').val(_settings.lastImportTime);
	});

	// EVENT: SETTINGS - REIMPORT
	$('div#settings a#reimportUrl').live('click', function(event, ui){
		_settings.lastImportUrl = '';
		_settings.lastImportTime = '';
		_settings.save();
		ImportXml(); //TODO: I think I want to do this by redirecting to the splash and have a check as part of the spash
	});

	// EVENT: SPLASH - SHOW
	$('div#splash').live('pageshow', function(event, ui) {
		// Start Queue
		$.mobile.changePage('#loading');
		Bistre.MobileBookCatalog.Core.Init();
	});

	// EVENT: LOADING - SHOW
	$('div#loading').live('pageshow', function(event, ui) {
	});

	// EVENT: TAGS - SHOW
	$('div#tags').live('pageshow', function(event, ui) {
		var $list = $(this).find('ul');
		var tags = _bookDb.allTags(function(tags) { 
		  var letter = '';
		  for (var idx in tags) {
			var tag = tags[idx];
			if (letter != tag.charAt(0).toUpperCase()) {
			  letter = tag.charAt(0).toUpperCase();
			  $list.append('<li data-role="list-divider">' + letter + '</li>');
			}
			$list.append('<li><a href="#">' + tag + '</a></li>');
			//$('div#tags').page(); // Reinit jQuery.Mobile page
			$list.listview('refresh');
		  }
		});
	});

	// EVENT: TAGS - HIDE
	$('div#tags').live('pagehide', function(event, ui) {
		var $list = $(this).find('ul');
		$list.html('');  // Clear out all HTML
	});
});
